﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Data;
using System.Text;
using System.Windows.Forms;

namespace LibExtend
{
    public partial class TableView : System.Windows.Forms.Panel
    {
        public delegate void ItemClickHandler(Table Item);
        public event ItemClickHandler ItemLicked;
        public event LibExtend.Events.DataExchangeHandler DataExchange;

        TableColls tableColls = new TableColls();
        public TableColls Items { get { return tableColls; } }

        public int ItemSize 
        {
            get { return iSize; }
            set { iSize = value; CalcRowCol(); }
        }
        [DefaultValue(0)]
        public int SperatorWidth { get; set; }

        public int RowNumber
        {
            get { return rowCount; }
            set { rowCount = value; }
        }
        public int ColNumber
        {
            get { return colCount; }
            set { colCount = value; }
        }
        public DataRow[] DataShow { get; set; }//Used for Finding table


        public LibExtend.MainView Owner { get; set; }
        public DataRow[] ItemData { get; set; }

        private DataTable DetailData = new DataTable();
        GraphicsPath path = new GraphicsPath();
        Table m_Hover = null;
        DetailForm currDetail;

        private int iSize = 84;
        private int rowCount = 0;
        private int colCount = 0;
        private int TotalItem = 0;

        public TableView()
        {
            InitializeComponent();
            this.AllowDrop = true;

            SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            SetStyle(ControlStyles.ResizeRedraw, true);
            SetStyle(ControlStyles.SupportsTransparentBackColor, true);

            this.BackColor = Color.Transparent;
        }

        public Table GetTable(Point Point)
        {
            return tableColls.Table(this.PointToClient(Point));
        }

        void f_DataExchange(LibExtend.Events.Sender sender)
        {
            if (this.DataExchange != null)
                this.DataExchange(sender);
        }

        public void Invalidate(Point MousePoint)
        {
            this.Invalidate();
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            if (TotalItem == 0) return;

            e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            Point _point = this.PointToClient(MousePosition);
            Table _c = tableColls.Table(_point);

            foreach (Table _cel in tableColls)
            {
                if (!IsVisible(_cel.IdBan)) continue;

                _cel.OnPaint(e, (object.Equals(_cel, m_Hover)) ? Table.MouseState.Hover : Table.MouseState.None);
            }
            if (Owner.isDrag && !object.Equals(_c, null))
            {
                Pen p = new Pen(new SolidBrush(Color.Red));
                p.DashStyle = System.Drawing.Drawing2D.DashStyle.DashDot;
                e.Graphics.DrawRectangle(p, _c.Bound);
                p.Dispose();
            }

            e.Graphics.DrawPath(new Pen(new SolidBrush(Color.Gray)), path);
        }

        private bool IsVisible(int v_IdTable)
        {
            if (object.Equals(DataShow, null) || DataShow.Length <= 0) return true;

            if (!object.Equals(DataShow, null) && DataShow.Length > 0)
            {
                foreach (DataRow _row in DataShow)
                {
                    if ((int)_row["IdBan"] == v_IdTable)
                        return true;
                }
            }
            return false;
        }

        protected override void OnMouseMove(MouseEventArgs e)
        {
            m_Hover = tableColls.Table(e.Location);
            if (!object.Equals(m_Hover, null)) Invalidate();

            if (e.Button == System.Windows.Forms.MouseButtons.Left)
            {
                Owner.StartDrag(this, m_Hover, new Point(25, 25));
            }
            base.OnMouseMove(e);
        }

        protected override void OnMouseClick(MouseEventArgs e)
        {
            base.OnMouseClick(e);

            Table item = tableColls.Table(this.PointToClient(MousePosition));

            if (object.Equals(item, null)) return;

            if (ItemLicked != null)
                ItemLicked(item);

            //int flags = WinAPI.AW_ACTIVATE | WinAPI.AW_HOR_POSITIVE;

            //DetailForm f = new DetailForm(500, flags);
            ////f.FormBorderStyle = FormBorderStyle.None;
            //f.TopLevel = false;

            //this.Controls.Add(f);
            //f.Location = new Point(0, 0);
            //f.BringToFront();
            //f.InnerWidth = this.Width;
            //f.InnerHeight = this.Height;
            //f.Number = item.TenBan;
            //f.DataExchange += new LibExtend.Events.DataExchangeHandler(f_DataExchange);
            //f.Item = item;

            //currDetail = f;

            //f.Show();
            ShowDetail(item);
        }

        private void ShowDetail(Table item)
        {
            int flags = WinAPI.AW_ACTIVATE | WinAPI.AW_HOR_POSITIVE;

            DetailForm f = new DetailForm(500, flags);
            //f.FormBorderStyle = FormBorderStyle.None;
            f.TopLevel = false;

            this.Controls.Add(f);
            f.Location = new Point(0, 0);
            f.BringToFront();
            f.InnerWidth = this.Width;
            f.InnerHeight = this.Height;
            f.Number = item.TenBan;
            f.DataExchange += new LibExtend.Events.DataExchangeHandler(f_DataExchange);
            f.Item = item;

            currDetail = f;

            f.Show();
        }

        protected override void OnMouseLeave(EventArgs e)
        {
            m_Hover = null;
            base.OnMouseLeave(e);
        }

        private void CalcRowCol()
        {
            TotalItem = (object.Equals(ItemData, null) || ItemData.Length <= 0) ? 0 : ItemData.Length;
            SperatorWidth = 20;

            if (TotalItem == 0) return;
            tableColls.Clear();
            colCount = this.Width / (ItemSize + SperatorWidth);
            if (colCount == 0) return;

            if (colCount >= TotalItem)
            {
                colCount = TotalItem;
                rowCount = 1;
            }
            else
            {
                rowCount = TotalItem / colCount;
                if (TotalItem % colCount > 0) rowCount++;
            }

            int iCol = 0, iRow = 0;

            for (int i = 0; i < TotalItem; i++)
            {
                if (iCol >= colCount)
                {
                    iRow++;
                    iCol = 0;
                }
                Table cel = new Table();
                //cel.Image = LibExtend.Properties.Resources.Table;
                cel.IdBan = Convert.ToInt32(ItemData[i]["IdBan"]);
                cel.TenBan = ItemData[i]["TenBan"].ToString();
                if (Convert.ToInt16(ItemData[i]["State"]) > 0)
                {
                    cel.iState = Table.State.Busy;
                    cel.IdBanHang = Convert.ToInt16(ItemData[i]["State"]);
                }
                else
                    cel.iState = Table.State.Empty;
                int iLeft = (iCol == 0) ? 4 : 0;
                cel.Bound = new Rectangle(iCol * (ItemSize + SperatorWidth) + iLeft, iRow * (ItemSize + SperatorWidth), ItemSize, ItemSize);
                tableColls.Add(cel);
                iCol++;
            }
        }

        protected override void OnResize(EventArgs eventargs)
        {
            base.OnResize(eventargs);

            if (this.Width < 64) this.Width = 64;
            if (this.Height < 64) this.Height = 64;

            CalcRowCol();

            Rectangle rect = new Rectangle(0, 0, this.ClientRectangle.Width - 2, this.ClientRectangle.Height - 2);
            path = LibExtend.GlassHelpers.Helpers.RoundCorners(rect, 4, LibExtend.GlassHelpers.Helpers.Corner.AllBottom);
            Invalidate();
        }

        public void AddItem(DataRow row)
        {
            if (!object.Equals(currDetail, null) && currDetail.Visible)
                currDetail.AddItem(row);
        }

        public void RunShowDetail(string textFind)
        {
            foreach (Table tbl in tableColls)
            {
                if (tbl.TenBan.ToLower() == textFind.ToLower())
                {
                    if (currDetail != null)
                        currDetail.Close();

                    if (ItemLicked != null)
                        ItemLicked(tbl);

                    ShowDetail(tbl);
                    return;
                }
            }
        }
    }
}
